import axios, { AxiosRequestConfig } from 'axios'
import router from '@/plugins/router'
import { ElNotification } from 'element-plus'
import { useUserStore } from '@/plugins/store'

interface RequestConfig extends AxiosRequestConfig {
  widthToken?: boolean;
  fullResponse?: boolean;
  rowResponse?: boolean;
  silence?: boolean;
}

export default function http<T = any>(params: RequestConfig): Promise<T> {
  if (!params.baseURL) {
    params.baseURL = import.meta.env.VITE_APP_API_BASE_URL
  }

  if (params.widthToken !==false) {
    const user = useUserStore()
    const headers = params.headers || {}
    headers.token = user.token
    params.headers = headers
  }
  
  return axios<T>(params).then(res => {
    if (params.rowResponse) {
      return res
    }
    const data = res.data as any;
    if (data.code === 401) {
      // ElNotification({
      //   title: '权限异常',
      //   message: data.msg,
      //   type: 'error',
      // })
      router.push({ name: 'Login' })
      return Promise.reject(data.msg)
    }
    if (data.code !== 0) {
      if (!params.silence) {
        ElNotification({
          title: '接口异常',
          message: data.msg,
          type: 'error',
        })
      }
      return Promise.reject(data.msg)
    }
    return params.fullResponse ? data : data && data.data
  })
}